const express = require('express');
const multer = require('multer');
const path = require('path');
const os = require("os");
const fs = require('fs');
const cors = require('cors');

// 创建uploads文件夹
if (!fs.existsSync('./uploads')) {
    fs.mkdirSync('./uploads');
}

// 获取网卡信息
const networkInterfaces = os.networkInterfaces();

// 设置存储位置和文件名
const storage = multer.diskStorage(
    {
        destination: function (req, file, cb) {
            // 存储文件的目录
            cb(null, 'uploads/')
        },
        filename: function (req, file, cb) {
            cb(null, file.originalname)
        }
    }
);

// 初始化multer
const upload = multer({storage: storage});

// 创建express应用
const app = express();
const port = 3000;

// 使用cors中间件，允许所有来源的请求
app.use(cors());

// 定义静态资源目录
app.use(express.static('public'));

// 路由：POST请求，处理文件上传
app.post(
    '/upload',
    upload.array('files'),
    (req, res) => {
        if (!req.files) {
            return res.send('No files were uploaded.');
        }

        // req.files 是一个数组，包含所有上传的文件信息
        console.log(req.files);

        // 成功上传后重定向或发送消息
        res.send('Files uploaded successfully!');
    }
);

// 获取 ./uploads 目录下的文件列表
app.get(
    '/getUploadFileList',
    (req, res) => {
        const directoryPath = path.join(__dirname, './uploads');

        fs.readdir(
            directoryPath,
            (err, files) => {
                if (err) {
                    return res.status(500)
                        .send(
                            {
                                message: "无法扫描目录: " + err,
                            }
                        );
                }

                const fileList = [];
                files.forEach(
                    (file) => {
                        fileList.push(
                            {
                                // 文件名
                                name: file,
                                // 文件创建时间
                                createTime: fs.statSync(path.join(directoryPath, file)).birthtime,
                            }
                        );
                    }
                );

                // 按时间倒序排列
                fileList.sort(
                    (a, b) => {
                        return b.createTime - a.createTime;
                    }
                );

                res.status(200).send(fileList);
            }
        );
    }
);

// 文件下载
app.get(
    '/download/:fileName',
    (req, res) => {
        const file = req.params.fileName;
        const filePath = path.join(__dirname, 'uploads', file);

        res.download(filePath);
    }
);

// 文件删除
app.get(
    '/delete/:fileName',
    (req, res) => {
        const file = req.params.fileName;
        const filePath = path.join(__dirname, 'uploads', file);

        fs.unlink(
            filePath,
            (err) => {
                if (err) {
                    return res.status(500).send(
                        {
                            message: "无法删除文件: " + err,
                        }
                    );
                }

                res.status(200).send()
            }
        )
    }
)

// 获取服务器二维码列表
app.get(
    '/getServerAddressList',
    (req, res) => {
        const ipAddresses = [];

        for (const interfaceName in networkInterfaces) {
            const networkInterface = networkInterfaces[interfaceName];
            for (const alias of networkInterface) {
                if (alias.family === 'IPv4' && !alias.internal) {
                    ipAddresses.push("http://" + alias.address + ":" + port);
                }
            }
        }

        res.status(200).send(ipAddresses);
    }
);

// 确保这个路由在其他路由之后定义
app.get(
    '*',
    (req, res) => {
        res.sendFile(path.join(__dirname, 'public', 'index.html'));
    }
);

// 启动服务器
app.listen(
    port,
    () => {
        console.log(`Server running at http://localhost:${port}`);
    }
);

